import json
from flask import Flask
from flask import request
from flask import current_app
from flask import jsonify

from utils.correction_result import correct

app = Flask(__name__)


@app.route('/api/v1/correction', methods=['GET', 'POST'])
def correction_service():
    if request.method == 'POST':
        post_param = request.get_data()
        try:
            result = json.loads(post_param)
            current_app.logger.debug(f'{request.path} input[+]{result}')

            right_answer = result['right_answer']
            user_answer = result['user_answer']
        except Exception as e:
            return jsonify({"code": 500, "data": {"score": ''}, "msg": f"请求失败:{e}"})

        try:
            result_score = correct(right_answer, user_answer)
            current_app.logger.debug(f'{request.path} succeed result_score [+]{result_score}')

            return jsonify({"code": 0, "data": {"score": result_score}, "msg": "请求成功"})

        except Exception as e:
            current_app.logger.debug(f'{request.path} error[+]{e}')
            return jsonify({"code": 500, "data": {"score": ''}, "msg": f"请求失败:{e}"})

    else:
        return jsonify({"code": 500, 'msg': "请发送post请求", "data": ""})
